<template>
  <div class="dashboard-container">
    <!-- 顶部概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-card class="stat-card" shadow="hover" @click="goToUserManagement">
            <div class="stat-content">
              <div class="stat-icon user-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">用户总数</div>
                <div class="stat-value">{{ stats.userCount }}</div>
                <div class="stat-trend">
                  <span :class="['trend', userTrend.type]">
                    <el-icon v-if="userTrend.icon === 'top'"><Top /></el-icon>
                    <el-icon v-else><Bottom /></el-icon>
                    {{ userTrend.value }}%
                  </span>
                  <span class="stat-period">较上月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="8">
          <el-card class="stat-card" shadow="hover" @click="goToProjectManagement">
            <div class="stat-content">
              <div class="stat-icon project-icon">
                <el-icon><Notebook /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">课题总数</div>
                <div class="stat-value">{{ stats.projectCount }}</div>
                <div class="stat-trend">
                  <span :class="['trend', projectTrend.type]">
                    <el-icon v-if="projectTrend.icon === 'top'"><Top /></el-icon>
                    <el-icon v-else><Bottom /></el-icon>
                    {{ projectTrend.value }}%
                  </span>
                  <span class="stat-period">较上月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="8">
          <el-card class="stat-card" shadow="hover" @click="goToApplicationManagement">
            <div class="stat-content">
              <div class="stat-icon application-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">申请总数</div>
                <div class="stat-value">{{ stats.applicationCount }}</div>
                <div class="stat-trend">
                  <span :class="['trend', applicationTrend.type]">
                    <el-icon v-if="applicationTrend.icon === 'top'"><Top /></el-icon>
                    <el-icon v-else><Bottom /></el-icon>
                    {{ applicationTrend.value }}%
                  </span>
                  <span class="stat-period">较上月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-area">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户增长趋势</span>
                <el-select
                  v-model="userChartRange"
                  size="small"
                  style="width: 100px"
                  @change="fetchUserChartData"
                >
                  <el-option label="近7天" value="7"></el-option>
                  <el-option label="近30天" value="30"></el-option>
                  <el-option label="近90天" value="90"></el-option>
                </el-select>
              </div>
            </template>
            <div class="chart-container">
              <VChart
                v-if="userChartData.labels.length > 0"
                :option="userChartOption"
                autoresize
              />
              <el-empty v-else description="暂无数据" />
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>课题状态分布</span>
              </div>
            </template>
            <div class="chart-container">
              <VChart
                v-if="projectChartData.series.length > 0"
                :option="projectChartOption"
                autoresize
              />
              <el-empty v-else description="暂无数据" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近活动和待办事项 -->
    <div class="activity-area">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="activity-card">
            <template #header>
              <div class="card-header">
                <span>最近活动</span>
              </div>
            </template>
            <div class="activity-list">
              <div
                v-for="(activity, index) in recentActivities"
                :key="index"
                class="activity-item"
              >
                <div class="activity-icon">
                  <i :class="activity.icon"></i>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-desc">{{ activity.description }}</div>
                  <div class="activity-time">{{ activity.time }}</div>
                </div>
              </div>
              <el-empty v-if="recentActivities.length === 0" description="暂无活动记录" />
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :lg="12">
          <el-card class="todo-card">
            <template #header>
              <div class="card-header">
                <span>待办事项</span>
                <el-button
                  type="text"
                  size="small"
                  @click="showAddTodoDialog = true"
                >
                  添加
                </el-button>
              </div>
            </template>
            <div class="todo-list">
              <div
                v-for="(todo, index) in todos"
                :key="index"
                class="todo-item"
                :class="{ completed: todo.completed }"
              >
                <el-checkbox
                  v-model="todo.completed"
                  @change="updateTodoStatus(todo)"
                />
                <div class="todo-content">
                  <div class="todo-title">{{ todo.title }}</div>
                  <div class="todo-desc">{{ todo.description }}</div>
                </div>
                <div class="todo-actions">
                  <el-button
                    type="text"
                    size="small"
                    @click="editTodo(todo)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="removeTodo(todo)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <el-empty v-if="todos.length === 0" description="暂无待办事项" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加/编辑待办事项弹窗 -->
    <el-dialog
      v-model="showAddTodoDialog"
      :title="isEditingTodo ? '编辑待办事项' : '添加待办事项'"
      width="500px"
    >
      <el-form :model="todoForm" label-width="80px">
        <el-form-item label="标题" required>
          <el-input v-model="todoForm.title" placeholder="请输入待办事项标题" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="todoForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入详细描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddTodoDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTodo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { User, Notebook, Document, Edit, Delete, Top, Bottom } from '@element-plus/icons-vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import { dashboardApi } from '@/api/admin';
import type {
  DashboardStats,
  UserChartData,
  ProjectChartData,
  ActivityItem,
  TodoItem
} from '@/api/adminTypes';
// 在原有导入基础上添加router
import { useRouter } from 'vue-router';

// 获取router实例
const router = useRouter();

// 添加跳转方法
const goToUserManagement = () => {
  router.push('/admin/user/list');
};

const goToProjectManagement = () => {
  router.push('/admin/project/list');
};

const goToApplicationManagement = () => {
  router.push('/admin/application/list');
};
// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
]);

// 统计数据
const stats = reactive<DashboardStats>({
  userCount: 0,
  userGrowth: 0,
  projectCount: 0,
  projectGrowth: 0,
  applicationCount: 0,
  applicationGrowth: 0
});

// 用户增长趋势
const userChartRange = ref('30');
const userChartData = reactive<UserChartData>({
  labels: [],
  data: []
});

// 课题状态分布
const projectChartData = reactive<ProjectChartData>({
  series: []
});

// 最近活动
const recentActivities = ref<ActivityItem[]>([]);

// 待办事项
const todos = ref<TodoItem[]>([]);
const showAddTodoDialog = ref(false);
const isEditingTodo = ref(false);
const currentTodoId = ref<number | null>(null);
const todoForm = reactive({
  title: '',
  description: ''
});

// 计算趋势数据
const userTrend = computed(() => {
  return {
    value: Math.abs(stats.userGrowth),
    icon: stats.userGrowth >= 0 ? 'top' : 'bottom',
    type: stats.userGrowth >= 0 ? 'up' : 'down'
  };
});

const projectTrend = computed(() => {
  return {
    value: Math.abs(stats.projectGrowth),
    icon: stats.projectGrowth >= 0 ? 'top' : 'bottom',
    type: stats.projectGrowth >= 0 ? 'up' : 'down'
  };
});

const applicationTrend = computed(() => {
  return {
    value: Math.abs(stats.applicationGrowth),
    icon: stats.applicationGrowth >= 0 ? 'top' : 'bottom',
    type: stats.applicationGrowth >= 0 ? 'up' : 'down'
  };
});

// 用户增长图表配置
const userChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: userChartData.labels,
    axisLine: {
      lineStyle: {
        color: '#dcdfe6'
      }
    },
    axisLabel: {
      color: '#606266'
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#dcdfe6'
      }
    },
    splitLine: {
      lineStyle: {
        color: ['#ebeef5'],
        type: 'dashed'
      }
    },
    axisLabel: {
      color: '#606266'
    }
  },
  series: [
    {
      name: '新增用户',
      type: 'line',
      smooth: true,
      data: userChartData.data,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(64, 158, 255, 0.5)'
            },
            {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.1)'
            }
          ]
        }
      }
    }
  ]
}));

// 课题状态图表配置
const projectChartOption = computed(() => ({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center',
    data: projectChartData.series.map(item => item.name)
  },
  series: [
    {
      name: '课题状态',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: projectChartData.series
    }
  ]
}));

// 修改统计数据接口
const fetchDashboardData = async () => {
  try {
    const res = await dashboardApi.getStats();
    stats.userCount = res.data.stats.userCount || 0;
    stats.projectCount = res.data.stats.projectCount || 0;
    stats.applicationCount = res.data.stats.applicationCount || 0;
    // 其他统计字段根据实际需求调整
  } catch (error) {
    console.error('获取仪表盘数据失败:', error);
    ElMessage.error('获取仪表盘数据失败');
  }
};

// 获取用户图表数据
const fetchUserChartData = async () => {
  try {
    const res = await dashboardApi.getUserChartData({
      days: parseInt(userChartRange.value)
    });
    userChartData.labels = res.data.labels;
    userChartData.data = res.data.data;
  } catch (error) {
    console.error('获取用户图表数据失败:', error);
    ElMessage.error('获取用户图表数据失败');
  }
};

// 获取课题图表数据
const fetchProjectChartData = async () => {
  try {
    const res = await dashboardApi.getProjectChartData();
    projectChartData.series = res.data.series;
  } catch (error) {
    console.error('获取课题图表数据失败:', error);
    ElMessage.error('获取课题图表数据失败');
  }
};

// 添加待办事项
const addTodo = () => {
  todoForm.title = '';
  todoForm.description = '';
  isEditingTodo.value = false;
  currentTodoId.value = null;
  showAddTodoDialog.value = true;
};

// 编辑待办事项
const editTodo = (todo: TodoItem) => {
  todoForm.title = todo.title;
  todoForm.description = todo.description || '';
  isEditingTodo.value = true;
  currentTodoId.value = todo.id;
  showAddTodoDialog.value = true;
};

// 保存待办事项
const saveTodo = async () => {
  if (!todoForm.title.trim()) {
    ElMessage.warning('请输入待办事项标题');
    return;
  }

  try {
    if (isEditingTodo.value && currentTodoId.value) {
      // 更新待办事项
      await dashboardApi.updateTodo(currentTodoId.value, todoForm);
      ElMessage.success('待办事项更新成功');
    } else {
      // 新增待办事项
      await dashboardApi.addTodo(todoForm);
      ElMessage.success('待办事项添加成功');
    }
    showAddTodoDialog.value = false;
    fetchDashboardData(); // 刷新数据
  } catch (error) {
    console.error('保存待办事项失败:', error);
    ElMessage.error('保存待办事项失败');
  }
};

// 更新待办事项状态
const updateTodoStatus = async (todo: TodoItem) => {
  try {
    await dashboardApi.updateTodoStatus(todo.id, { completed: todo.completed });
  } catch (error) {
    console.error('更新待办事项状态失败:', error);
    // 回滚状态
    todo.completed = !todo.completed;
    ElMessage.error('更新状态失败');
  }
};

// 删除待办事项
const removeTodo = async (todo: TodoItem) => {
  try {
    await ElMessageBox.confirm('确定要删除该待办事项吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await dashboardApi.deleteTodo(todo.id);
    ElMessage.success('删除成功');
    fetchDashboardData(); // 刷新数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除待办事项失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 初始化数据
onMounted(() => {
  fetchDashboardData();
  fetchUserChartData();
  fetchProjectChartData();
});
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.overview-cards {
  margin-bottom: 20px;
  .stat-card {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }
  .stat-card {
    margin-bottom: 20px;
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .stat-content {
      display: flex;
      align-items: center;

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        font-size: 24px;
        color: white;

        &.user-icon {
          background-color: #409EFF;
        }

        &.project-icon {
          background-color: #67C23A;
        }

        &.application-icon {
          background-color: #E6A23C;
        }
      }

      .stat-info {
        flex: 1;

        .stat-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 5px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;
        }

        .stat-trend {
          font-size: 12px;
          color: #909399;

          .trend {
            margin-right: 5px;

            &.up {
              color: #67C23A;
            }

            &.down {
              color: #F56C6C;
            }
          }
        }
      }
    }
  }
}

.chart-area {
  margin-bottom: 20px;

  .chart-card {
    margin-bottom: 20px;
    border-radius: 8px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 300px;
    }
  }
}

.activity-area {
  .activity-card, .todo-card {
    margin-bottom: 20px;
    border-radius: 8px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .activity-list, .todo-list {
      max-height: 400px;
      overflow-y: auto;
    }

    .activity-item {
      display: flex;
      padding: 12px 0;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .activity-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        color: #409EFF;
        font-size: 18px;
      }

      .activity-content {
        flex: 1;

        .activity-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
        }

        .activity-desc {
          font-size: 12px;
          color: #909399;
          margin-bottom: 4px;
        }

        .activity-time {
          font-size: 12px;
          color: #C0C4CC;
        }
      }
    }

    .todo-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      &.completed {
        .todo-content {
          .todo-title {
            text-decoration: line-through;
            color: #909399;
          }
        }
      }

      .el-checkbox {
        margin-right: 15px;
      }

      .todo-content {
        flex: 1;

        .todo-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
        }

        .todo-desc {
          font-size: 12px;
          color: #909399;
        }
      }

      .todo-actions {
        opacity: 0;
        transition: opacity 0.3s;

        .el-button {
          padding: 0;
          margin-left: 10px;
        }
      }

      &:hover {
        .todo-actions {
          opacity: 1;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .overview-cards {
    .stat-card {
      .stat-content {
        .stat-icon {
          width: 50px;
          height: 50px;
          margin-right: 15px;
          font-size: 20px;
        }

        .stat-info {
          .stat-value {
            font-size: 20px;
          }
        }
      }
    }
  }

  .activity-item, .todo-item {
    padding: 10px 0;
  }
}
</style>
